<template>
  <MainLayout title="菜单管理">
    <template #main>
      <div class="main_block">
        <SearchLayout>
          <template #search>
            <el-input
              v-model="search_params.queryParams.menuName"
              placeholder="请输入菜单名称"
              clearable
              class="search_item"
            />
            <el-button type="primary" @click="handleSearchList('saerch')"
              >搜索</el-button
            >
            <el-button @click="handleSearchReset">重置</el-button>
            <el-button type="success" @click="handleAddMeun"
              >新增菜单</el-button
            >
          </template>
          <template #table>
            <el-table
              :data="table_list"
              border
              v-loading="table_loading"
              :style="{ height: 'calc(100vh - 260px)' }"
            >
              <el-table-column
                label="序号"
                width="55"
                type="index"
                align="center"
              />
              <el-table-column
                prop="menuName"
                label="菜单名称"
                min-width="120"
                align="center"
              />
              <el-table-column
                prop="menuParentName"
                label="上级菜单"
                min-width="120"
                align="center"
              >
              </el-table-column>
              <el-table-column
                prop="sn"
                label="排序"
                min-width="80"
                align="center"
              />
              <el-table-column
                prop="showType"
                label="跳转方式"
                min-width="100"
                align="center"
              >
                <template #default="{ row }">
                  <div>{{ handleJupMethod(row.showType) }}</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="isDefault"
                label="是否默认"
                min-width="100"
                align="center"
              >
                <template #default="{ row }">
                  <el-switch
                    :model-value="row.isDefault"
                    size="small"
                    active-value="1"
                    inactive-value="0"
                    @change="handleDefaultChange(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="isUserSee"
                label="用户是否可见"
                min-width="100"
                align="center"
              >
                <template #default="{ row }">
                  {{ handleYesorNo(row.isUserSee) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="createTime"
                label="创建时间"
                min-width="120"
                align="center"
              >
                <template #default="{ row }">
                  {{ iso8601ToTime(row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="100"
                fixed="right"
                align="center"
              >
                <template #default="{ row }">
                  <div class="flex_block_around operate_block">
                    <div
                      class="color_primary cursor_pointer"
                      @click="handleEdit(row)"
                    >
                      编辑
                    </div>
                    <div
                      class="color_delete cursor_pointer"
                      @click="handleDelete(row)"
                    >
                      删除
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <Pagination
              :page="search_params.pageNum"
              :size="search_params.pageSize"
              :total="table_total"
              @change="handlePaginationChange"
            ></Pagination>
          </template>
        </SearchLayout>
      </div>
    </template>
  </MainLayout>
  <el-dialog
    v-model="isShowDialog"
    :title="`${dialog_state ? '新增' : '编辑'}菜单`"
    width="600"
    :before-close="handleDialogClose"
    :close-on-click-modal="false"
  >
    <div class="dialog_main">
      <el-form
        ref="form_ref"
        :model="form_params"
        label-width="120"
        :rules="form_rules"
        style="max-width: 500px"
      >
        <el-form-item label="菜单图标：" prop="menuIconUrl">
          <div class="flex_block_between">
            <IconSelect v-model="form_params.menuIconUrl"></IconSelect>
            <el-icon class="ml20 pointer" @click="handleDeleteIcon"
              ><Delete
            /></el-icon>
          </div>
        </el-form-item>

        <el-form-item label="菜单名称：" prop="menuName">
          <el-input
            v-model="form_params.menuName"
            clearable
            placeholder="请输入菜单名称"
          />
        </el-form-item>
        <el-form-item label="上级名称：" prop="menuParentId">
          <el-select
            v-model="form_params.menuParentId"
            placeholder="请选择上级名称"
            clearable
          >
            <el-option
              class="select_item"
              v-for="item in table_list"
              :key="item.menuId"
              :label="item.menuName"
              :value="item.menuId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序：" prop="sn">
          <el-input
            v-model="form_params.sn"
            @blur="handleSnNumber"
            clearable
            placeholder="请输入排序"
            type="number"
            :max="99999"
            :maxlength="5"
          />
        </el-form-item>
        <el-form-item label="跳转方式：" prop="showType">
          <el-select
            v-model="form_params.showType"
            placeholder="请选择跳转方式"
          >
            <el-option
              class="select_item"
              v-for="item in jump_method_list"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="URL：" prop="menuUrl">
          <el-input
            v-model="form_params.menuUrl"
            clearable
            placeholder="请输入URL"
          />
        </el-form-item>
        <el-form-item label="用户是否可看：" prop="isUserSee">
          <el-radio-group v-model="form_params.isUserSee">
            <el-radio
              :value="item.value"
              size="large"
              v-for="item in yes_no_list"
              :key="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否默认：" prop="isDefault">
          <el-radio-group v-model="form_params.isDefault">
            <el-radio
              :value="item.value"
              size="large"
              v-for="item in yes_no_list"
              :key="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button
          type="primary"
          :loading="form_loading"
          @click="handleDialogConfirm"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  AdminMenuAdd,
  AdminMenuEdit,
  AdminMenuDelete,
} from "@/api/settings.js";
import { AdminMenuList } from "@/api/user.js";

import { nextTick, ref } from "vue";
import { iso8601ToTime } from "@/utils/index.js";
import {
  jump_method_list,
  handleJupMethod,
  yes_no_list,
  handleYesorNo,
} from "@/api/common.js";

const search_params = reactive({
  pageNum: 1,
  pageSize: 10,
  queryParams: {
    menuName: "",
  },
});
const table_loading = ref(false);
const table_total = ref(0);
const table_list = ref([]);
const isShowDialog = ref(false);
const dialog_state = ref(true);
const form_params = ref({
  menuName: "",
  menuKey: "",
  menuUrl: "",
  menuParentId: "",
  menuIconUrl: "",
  showType: "",
  path: "",
  sn: "",
  isUserSee: "0",
  isDefault: "0",
});
const form_rules = reactive({
  menuName: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  menuUrl: [{ required: true, message: "请输入菜单路径", trigger: "blur" }],
  isUserSee: [{ required: true, message: "用户是否可见", trigger: "blur" }],
  isDefault: [{ required: true, message: "是否默认", trigger: "blur" }],
  // sn: [{ required: true, message: "请选择排序", trigger: "blur" }],
  showType: [{ required: true, message: "请选择跳转方式", trigger: "change" }],
});
const edit_info = ref({});

onMounted(() => {
  handleSearchList(); //获取列表数据
});

const handleSearchReset = () => {
  search_params.queryParams.menuName = "";
  handleSearchList(); //获取列表数据
};
const handleSearchList = (type) => {
  if (type === "search") {
    search_params.pageNum = 1;
  }
  table_loading.value = true;
  AdminMenuList(search_params)
    .then((res) => {
      let list = res.list || [];
      list.forEach((item) => {
        let reslut = list.find((val) => val.menuId == item.menuParentId);
        if (reslut) {
          item.menuParentName = reslut.menuName; //父节点名称
        }
      });
      // 排序
      list.sort((a, b) => {
        return Number(a.sn || 999999) - Number(b.sn || 999999); //没填的就放在最后
      });
      table_list.value = list;
      table_total.value = res.total;
    })
    .finally(() => {
      table_loading.value = false;
    });
};
const handlePaginationChange = (value) => {
  search_params.pageNum = value.page;
  search_params.pageSize = value.size;
  handleSearchList();
};
const handleDeleteIcon = () => {
  form_params.value.menuIconUrl = "";
};
const form_ref = ref(null);
const form_loading = ref(false);

const handleAddMeun = () => {
  isShowDialog.value = true;
};
const handleEdit = (item) => {
  edit_info.value = JSON.parse(JSON.stringify(item));
  form_params.value = edit_info.value;

  dialog_state.value = false;
  isShowDialog.value = true;
};
const handleDialogClose = () => {
  let obj = {
    menuName: "",
    menuKey: "",
    menuUrl: "",
    menuParentId: "",
    menuIconUrl: "",
    showType: "",
    path: "",
    sn: "",
    isUserSee: "0",
    isDefault: "0",
  };
  form_params.value = obj;

  dialog_state.value = true;
  form_ref.value.resetFields();
  isShowDialog.value = false;
};
const handleDialogConfirm = () => {
  form_ref.value.validate((valid) => {
    if (valid) {
      if (dialog_state.value) {
        form_loading.value = true;
        AdminMenuAdd(form_params.value)
          .then((res) => {
            handleDialogClose();
            ElMessage.success("菜单添加成功");
            handleSearchList();
          })
          .finally(() => {
            form_loading.value = false;
          });
      } else {
        let obj = {};
        form_loading.value = true;
        obj.menuId = edit_info.value.menuId;
        obj.menuName = form_params.value.menuName;
        obj.menuKey = form_params.value.menuKey;
        obj.menuUrl = form_params.value.menuUrl;
        obj.menuParentId = form_params.value.menuParentId;
        obj.menuIconUrl = form_params.value.menuIconUrl;
        obj.showType = form_params.value.showType;
        obj.path = form_params.value.path;
        obj.sn = form_params.value.sn;
        obj.isUserSee = form_params.value.isUserSee;
        obj.isDefault = form_params.value.isDefault;
        obj.createTime = edit_info.value.createTime;
        obj.updateTime = edit_info.value.updateTime;
        AdminMenuEdit(obj)
          .then((res) => {
            handleDialogClose();
            ElMessage.success("菜单编辑成功");
            handleSearchList();
          })
          .finally(() => {
            form_loading.value = false;
          });
      }
    }
  });
};
const handleDefaultChange = (item) => {
  let text = "默认";
  if (item.isDefault == 1) text = "不默认";
  ElMessageBox.confirm(
    `确定要将该菜单的默认状态修改为 ${text} 吗？`,
    "温馨提示",
    {
      confirmButtonText: "确 定",
      cancelButtonText: "取 消",
      type: "warning",
    }
  )
    .then(() => {
      (item.isDefault = item.isDefault == 1 ? "0" : "1"),
        (table_loading.value = true);
      AdminMenuEdit(item).then((res) => {
        ElMessage.success("菜单状态编辑成功");
        handleSearchList();
      });
    })
    .finally(() => {
      table_loading.value = false;
    })
    .catch(() => {});
};
const handleDelete = (item) => {
  ElMessageBox.confirm(`确定要删除将该菜单吗？`, "温馨提示", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning",
  })
    .then(() => {
      let obj = {
        Id: item.menuId,
      };
      table_loading.value = true;
      AdminMenuDelete(obj).then((res) => {
        ElMessage.success("菜单删除成功");
        handleSearchList();
      });
    })
    .finally(() => {
      table_loading.value = false;
    })
    .catch(() => {});
};
const handleSnNumber = () => {
  if (!Number(form_params.value.sn) || Number(form_params.value.sn) > 99999) {
    form_params.value.sn = 99999;
  } else if (Number(form_params.value.sn) < -999) {
    form_params.value.sn = -999;
  }
};
</script>
<style scoped lang="scss">
.main_block {
  height: 100%;
  width: 100%;
  background-color: #fff;
  padding: 10px;
}
.search_item {
  width: 200px;
  margin-right: 8px;
}
</style>
